#include "head.h"

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n" << endl;
}

// ./udpclient serverip serverport
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);        // 主机序列转为网络序列
    server.sin_addr.s_addr = inet_addr(serverip.c_str());   // 将字符串ip转为网络4字节ip
    socklen_t len = sizeof(server);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "socker err" << endl;
        return 1;
    }

    // clint 也要bind

    string message;
    char buffer[1024];
    while(true)
    {
        memset(&buffer, 0, sizeof(buffer));
        cout << "Plase Enter@ ";
        getline(cin, message);

        // 1.数据 2.给谁发
        sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr*)&server, len);

        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sockfd, buffer, 1023, 0, (sockaddr*)&temp, &len);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << buffer << endl;
        }
    }

    close(sockfd);
    return 0;
}